package com.kuang.config;

import com.kuang.filter.TokenAuthFilter;
import com.kuang.filter.TokenLoginFilter;
import com.kuang.security.TokenLogoutHandler;
import com.kuang.security.TokenManager;
import com.kuang.security.UnAuthEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configurable
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class TokenSecurityConfig extends WebSecurityConfigurerAdapter {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
    private UserDetailsService userDetailsService;

    @Autowired
    public TokenSecurityConfig(TokenManager tokenManager, RedisTemplate redisTemplate, UserDetailsService userDetailsService) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.userDetailsService = userDetailsService;
    }

    /**
     * 设置角色的权限 ---> 所能访问的路径做出限制
     * */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors() // 允许跨域
                // 关闭csrf
                .and().csrf().disable()
                // 要求所有接口都需要做权限认证
                .authorizeRequests()
                .antMatchers("/user/**").permitAll() //设置哪些路径取消拦截
                .antMatchers("/teacher/**").hasAnyRole("teacher","admin")
                .antMatchers("/student/**").hasAnyRole("student","admin")
                .antMatchers("/admin/**").hasAnyRole("admin")
                .anyRequest().authenticated()
                .and().exceptionHandling()
                // 没有权限时的处理方案
                .authenticationEntryPoint(new UnAuthEntryPoint())
                // 注销路径
                .and().logout().logoutUrl("/user/logout")
                // 注销处理器: 准备专门操作token的类 + redisTemplate
                .addLogoutHandler(new TokenLogoutHandler(tokenManager,redisTemplate))
                .and()
                // 处理登录的逻辑
                .addFilter(new TokenLoginFilter(authenticationManager(),tokenManager,redisTemplate))
                // 处理权限的filter
                .addFilter(new TokenAuthFilter(authenticationManager(),tokenManager,redisTemplate))
                .httpBasic();
    }
    /**
     * 获得用户名和密码 ---> 进行用户授权
     * */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    /**
     * 一般用于配置全局的某些通用事物 ---> 静态资源
     * */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().
                antMatchers("/css/**", "/js/**","/image/**");
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
